package net.phoenix.repository.query;

import java.util.Map;

import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.Workspace;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.Query;
import javax.jcr.version.VersionException;

import net.phoenix.repository.BasicRepository;
import net.phoenix.repository.BasicSession;
import net.phoenix.repository.BasicWorkspace;

/**
 * 
 * @author lixf
 * 
 */
public abstract class GeneralQuery implements Query {
	protected String statement;
	protected BasicWorkspace workspace;
	protected BasicSession session;
	protected Node node;
	protected long limit = 100;
	protected long offset =0;


	public GeneralQuery(){	
		
	}
	
	public void init(Workspace workspace, String statement) throws InvalidQueryException{
		this.workspace = (BasicWorkspace)workspace;
		this.session = (BasicSession)workspace.getSession();
		this.limit = 20l;
		this.offset = 0l;
		this.node = null;
		this.statement = statement;
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.query.Query#setLimit(long)
	 */
	@Override
	public void setLimit(long limit) {
		this.limit = limit;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.query.Query#setOffset(long)
	 */
	@Override
	public void setOffset(long offset) {
		this.offset = offset;
	}

	public long getLimit() {
		return limit;
	}

	public long getOffset() {
		return offset;
	}

	public BasicWorkspace getWorkspace() {
		return workspace;
	}

	
	protected void setStatement(String statement) {
		this.statement = statement;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.query.Query#getStatement()
	 */
	@Override
	public String getStatement() {
		return this.statement;
	}
	
	
	@Override
	public Node storeAsNode(String absPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, UnsupportedRepositoryOperationException,
			RepositoryException {
		if(this.node!=null)
			return this.node;
		Node root = this.workspace.getSession().getRootNode();
		node = root.addNode("queries");
		node.setProperty("statement", this.getStatement());
		node.setProperty("language", this.getLanguage());
		node.save();
		return node;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.jcr.query.Query#getStoredQueryPath()
	 */
	@Override
	public String getStoredQueryPath() throws ItemNotFoundException, RepositoryException {
		if(this.node == null)
			throw new ItemNotFoundException("The query has not stored yet. ");
		return this.node.getPath();
	}

}
